package com.macro.mall.controller.ums;

import com.github.pagehelper.Page;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.exception.BusinessException;
import com.macro.mall.dto.ums.PagedQueryMemberAddressReqDto;
import com.macro.mall.ums.domain.MemberAddress;
import com.macro.mall.ums.entity.MemberAddressEntity;
import com.macro.mall.ums.service.address.MemberAddressService;
import com.macro.mall.ums.service.address.bo.PagedQueryMemberAddressInput;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 会员收货地址控制器
 *
 * @author xuyanjun
 * @date 2020-01-04
 */
@Api(tags = "会员收货地址")
@Slf4j(topic = "MemberAddressController")
@RestController
@RequestMapping("/memberAddress")
public class MemberAddressController {

    @Autowired
    private MemberAddressService memberAddressService;

    /**
     * 分页查询会员收货地址
     *
     * @return 分页后的会员收货地址
     */
    @ApiOperation("分页查询会员收货地址")
    @PostMapping("pagedQuery")
    public CommonPage<MemberAddress> pagedQuery(@RequestBody PagedQueryMemberAddressReqDto reqDto) {
        PagedQueryMemberAddressInput pagedQueryMemberAddressInput = new PagedQueryMemberAddressInput();
        pagedQueryMemberAddressInput
                .setMemberId(reqDto.getMemberId())
                .setPageIndex(reqDto.getPageIndex())
                .setPageSize(reqDto.getPageSize());

        Page<MemberAddressEntity> memberAddressEntities = memberAddressService.pagedQuery(pagedQueryMemberAddressInput);
        List<MemberAddress> memberAddresses = memberAddressService.entityToDomain(memberAddressEntities);

        return CommonPage.restPage(memberAddresses,memberAddressEntities);
    }

    /**
     * 根据id获取会员收货地址
     *
     * @param id id
     * @return 会员收货地址
     */
    @ApiOperation("根据id获取会员收货地址")
    @GetMapping("{id}")
    public CommonResult<MemberAddress> getById(@PathVariable long id) {
        if (id <= 0) {
            throw new BusinessException("要获取的会员收货地址Id不能为空。");
        }

        MemberAddressEntity memberAddressEntity = memberAddressService.getById(id);
        if (memberAddressEntity == null) {
            throw new BusinessException(String.format("要获取的会员收货地址id:%s不存在。", id));
        }

        MemberAddress memberAddress = memberAddressService.entityToDomain(memberAddressEntity);
        return CommonResult.success(memberAddress);
    }

}

